#pragma once

#include <iostream>
#include <sys/select.h>
#include <sys/time.h>
#include "Sockets.hpp"

using namespace std;

static const uint16_t defaultport = 8080;
const int fd_num_max = 1024;
const int defaultfd = -1;

class SelectServer
{
public:
    SelectServer(uint16_t port = defaultport)
        : _port(port)
    {
        for (int i = 0; i < fd_num_max; i++)
            _fd_array[i] = defaultfd;
    }

    bool Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
    }

    void Start()
    {
        _fd_array[0] = _listensock.Fd();
        int maxfd = _fd_array[0];
        for (;;)
        {
            fd_set rfds;
            FD_ZERO(&rfds);

            for (int i = 0; i < fd_num_max; i++)
            {
                if (_fd_array[i] == defaultfd)
                    continue;
                FD_SET(_fd_array[i], &rfds);
                if (maxfd < _fd_array[i])
                {
                    maxfd = _fd_array[i];
                    log(Info, "max fd update, max fd is: %d", maxfd);
                }
            }

            struct timeval timeout = {3, 0};

            int n = select(maxfd + 1, &rfds, nullptr, nullptr, /*&timeout*/ nullptr);
            switch (n)
            {
            case 0:
                cout << "time out: " << timeout.tv_sec << "." << timeout.tv_usec << endl;
                break;
            case -1:
                cerr << "select error" << endl;
                break;
            default:
                cout << "Time is ready!!!" << endl;
                Dispatcher(rfds);
                break;
            }
        }
    }

    void Dispatcher(fd_set &rfds)
    {
        for (int i = 0; i < fd_num_max; i++)
        {
            int fd = _fd_array[i];
            if (fd == defaultfd)
                continue;

            if (FD_ISSET(fd, &rfds))
            {
                if (fd == _listensock.Fd())
                    Accepter();
                else
                    Recver(fd, i);
            }
        }
    }

    void Accepter()
    {
        string clientip;
        uint16_t clientport;
        int sock = _listensock.Accept(&clientip, &clientport);
        if (sock < 0)
            return;
        log(Info, "accept success, %s: %d, sock fd: %d", clientip.c_str(), clientport, sock);

        int pos = 1;
        for (; pos < fd_num_max; pos++)
        {
            if (_fd_array[pos] != defaultfd)
                continue;
            else
                break;
        }
        if (pos == fd_num_max)
        {
            log(Warning, "server is full, close %d now!", sock);
            close(sock);
        }
        else
        {
            _fd_array[pos] = sock;
            PrintFd();
        }
    }

    void Recver(int fd, int pos)
    {
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "get a message: " << buffer;
        }
        else if (n == 0)
        {
            log(Info, "client quit, me too, close fd is : %d", fd);
            close(fd);
            _fd_array[pos] = defaultfd;
        }
        else
        {
            log(Warning, "read error, close fd is : %d", fd);
            close(fd);
            _fd_array[pos] = defaultfd;
        }
    }

    void PrintFd()
    {
        cout << "online fd list: ";
        for (int i = 0; i < fd_num_max; i++)
        {
            if (_fd_array[i] == defaultfd)
                continue;
            cout << _fd_array[i] << " ";
        }
        cout << endl;
    }

    ~SelectServer()
    {
        _listensock.Close();
    }

private:
    Sockets _listensock;
    uint16_t _port;
    int _fd_array[fd_num_max];
};
